﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DevSky.WebParts.DBConnectWP
{
    public class DBTools
    {
        //private static string fullSelectStatement = string.Empty;
        public static string FullSelectStatement(List<CustomDataColumn> columns, string tableName)
        {
            StringBuilder selectStatement = new StringBuilder("SELECT [SELECTFIELDLIST] FROM ");
            selectStatement.AppendFormat("[{0}]",tableName);
            StringBuilder fields = new StringBuilder();
            foreach (CustomDataColumn column in columns.Where(col => col.IsVisible || col.IsUniqueColumn))
            {
                if (column.IsLookupColumn)  // build join statement
                {
                    fields.AppendFormat(",{0}", column.Lookup.DisplayField); // add loopup display field
                    selectStatement.AppendFormat(" LEFT OUTER JOIN [{0}] ON [{2}].[{3}] = [{0}].[{1}]", column.Lookup.DBObjectName, column.Lookup.KeyField, tableName, column.Name);
                }
                else
                    fields.AppendFormat(",{0}", column.Name);
            }
            return selectStatement.ToString().Replace("[SELECTFIELDLIST]", fields.ToString().Substring(1));
        }
    }
}
